import axios from 'axios'
import { getUrlTabId } from '../utils/tools'

const transformResponse = function (res) {
    res = res.replace(/\"product_id\":(\d+)/g, '"product_id":"$1"')

    res = res.replace(/\"size_info_template_id\":(\d+)/g, '"size_info_template_id":"$1"')
    return JSON.parse(res)
}
const service = axios.create({
    // baseURL: env.BASE_URL,
    timeout: 200000,
    transformResponse
})
service.interceptors.request.use(
    async (config) => {
        config.baseURL = config.baseURL || 'http://127.0.0.1:8080'
        if (config.baseURL == 'https://fxg.jinritemai.com/') {
            if (config.param) {
                config.param._lid = String(Date.now()).substr(5) + String(Math.random()).substr(2, 4)
                config.param.appid = 1
                config.param._ = new Date().getTime()
            } else {

            }
        }

        if (!/\?/.test(config.url) && config.baseURL == 'https://fxg.jinritemai.com/') {
            let str = splitJoint(config.param)
            config.url += str
        }
        config.headers['Content-Type'] = 'application/json'
        if (config.method === 'post' || config.method === 'POST') {
            // config.data = {
            //     ...paramData,
            //     // ...config.data,
            // }
        }
        return config
    },
    (error) => {
        Promise.reject(error)
    }
)

function splitJoint(obj) {
    let arr = []
    for (let key in obj) {
        arr.push(key + '=' + obj[key])
    }
    return arr.length > 0 ? '?' + arr.join('&') : ''
}
service.interceptors.response.use(
    async (response) => {
        if (response.data.code === 0) {
            return response.data
        }
        if (response.data.code == "10008") {
            // console.log('登陆过期 刷新自动前端页面')
            const getIdtabs = await getUrlTabId('https://fxg.jinritemai.com')
            console.log('getIdtabs', getIdtabs)
            //缓存请求 等待刷新过后再次进入请求
            if (getIdtabs) {
                // chrome.tabs.reload(getIdtabs.id, () => {
                //     console.log('页面已经刷新')
                // })
            }
        }
    },
    (error) => {
        console.log('errorNET', error)
        return Promise.reject(error)
    }
)
export default service